1436B - Prime Square - CodeForces Solution


constructive algorithms math *900

Please click on ads to support us..

Python Code:

import math
def isprime(t):
    for i in range(2,int(math.sqrt(t))+1):
        if t%i==0:
            return False
    return True
def hi(t):
    r=1
    while(True):
        if not(isprime(r)):
            if(isprime(((t-1)*(t))+r)):
                return r
        r+=1

for _ in range(int(input())):
    n=int(input())
    if n==1:print(1)
    elif isprime(n):
        for i in range(n):
            for j in range(n):
                print(1,end=' ')
            print()
    else:
                                x=hi(n)
        for i in range(n):
            for j in range(n):
                if i==j:print(x,end=' ')
                else:print(n,end=' ')
            print()

C++ Code:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    long long int a, b, c, i, j, k, m, n, o, l, r, f = 0, cnt = 0, sum = 0, total = 0, mn = INT_MAX, mx = INT_MIN, sz, len, temp, pos, tc, x, y, z, arr[100000], brr[120];
    vector<long long int> vrr;
    string s;

    cin>>tc;
    while(tc--)
    {
        cin>>n;
        f = 0;
        map<int, int> mp;
        for( i = 2; i < 200 ; i++ )
        {
            f = 1;
            for( j = 2 ; j < i ; j++ )
            {
                if( i%j == 0 ) f = 0;
            }
            if(f) mp[i] = 1;
        }

        if( mp[n] )
        {
            for( i = 1; i<= n; i++ )
            {
                for( j = 1; j <= n; j++ )
                {
                  cout<< 1 << " ";

                }
                cout<< endl;
            }
        }
        else
        {
            for( i = n+1; 1 ; i++ )
            {
                if( mp[i] )
                {
                    x =i - (n-1);
                    if( mp[x] == 0 ) break;
                }
            }

            for( i = 1; i<= n; i++ )
            {
                for( j = 1; j <= n; j++ )
                {
                    if( i == j ) cout<< x << " ";
                    else cout<< 1 << " ";
                }
                cout<< endl;
            }
        }
    }



}


Comments

Submit
0 Comments
More Questions

236A - Boy or Girl
271A - Beautiful Year
520B - Two Buttons
231A - Team
479C - Exams
1030A - In Search of an Easy Problem
158A - Next Round
71A - Way Too Long Words
160A - Twins
1A - Theatre Square
1614B - Divan and a New Project
791A - Bear and Big Brother
1452A - Robot Program
344A - Magnets
96A - Football
702B - Powers of Two
1036A - Function Height
443A - Anton and Letters
1478B - Nezzar and Lucky Number
228A - Is your horseshoe on the other hoof
122A - Lucky Division
1611C - Polycarp Recovers the Permutation
432A - Choosing Teams
758A - Holiday Of Equality
1650C - Weight of the System of Nested Segments
1097A - Gennady and a Card Game
248A - Cupboards
1641A - Great Sequence
1537A - Arithmetic Array
1370A - Maximum GCD